package ar.edu.utn.frba.tacs.warnes.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

import ar.edu.utn.frba.tacs.warnes.BaseEntity;
import ar.edu.utn.frba.tacs.warnes.utils.SessionWarnes;

/**
 * 
 * @author dmiglino
 *
 * @param <T extends BaseEntity>
 */
public abstract class BaseDaoImpl<T extends BaseEntity> implements BaseDao<T> {
	private Session session;
	
	public Session getSession() {
		this.session = SessionWarnes.crearSession();
		return this.session;
	}

	public abstract Class<T> getModelClass();

	public List<T> list() throws IllegalArgumentException {
		return list(this.getModelClass());
	}

	@SuppressWarnings("unchecked")
	public List<T> list(Class<? extends BaseEntity> klass)
			throws IllegalArgumentException {
		Criteria criter = getSession().createCriteria(klass);
		List<T> lista = (List<T>) criter.list();
		return lista;
	}

	public void save(T obj) throws IllegalArgumentException {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.save(obj);
		transaction.commit();
	}

	public void delete(T obj) throws IllegalArgumentException {
		Session session = getSession();
		Transaction transaction = session.beginTransaction();
		session.delete(obj);
		transaction.commit();
	}
	
	@SuppressWarnings("unchecked")
	public int count() {
		Criteria criter = getSession().createCriteria(this.getModelClass());
		List<T> lista = (List<T>) criter.list();
		return lista.size();
	}

	@SuppressWarnings("unchecked")
	public T uniqueResult(Long id) {
		Criteria criter = getSession().createCriteria(this.getModelClass());
		criter.add(Restrictions.like("id", id));
		T entity =  (T) criter.uniqueResult();
		return entity;
	}

}
